package com.five.api.controller;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * 文件同意下载控制器
 * @author Administrator
 *
 */
@RequestMapping("/download")
@Controller
@Api(tags = "统一文件下载接口")
@CrossOrigin
public class DownloadController {


	private String uploadVideoPath = "D:\\qf\\data\\video\\";//视频保存位置

	private String uploadImgPath = "D:\\qf\\data\\img\\";//图片保存位置

	//分片上传视频保存路径
	@Value("${five.upload.video.path}")
	private String decryptFilePath;
	
	/**
	 * 视频文件下载方法
	 * @param filename
	 * @param response
	 */
	@RequestMapping(value = "/download_video",method = RequestMethod.GET)
	@ApiOperation("视频下载接口")
	public void downloadVideoFile(@RequestParam(name="filename",required=true)String filename, HttpServletResponse response, HttpServletRequest request){
		filename = uploadVideoPath + File.separator + filename;
		File file = new File(filename);
		//设置返回文件大小
		response.setContentLength(Integer.valueOf(file.length()+""));
		//设置返回类型
		try {
			response.setContentType(Files.probeContentType(Paths.get(filename)));
		} catch (Exception e) {
			e.printStackTrace();
		}
		String rangeString = request.getHeader("Range");//如果是video标签发起的请求就不会为null
		long range = Long.valueOf(rangeString.substring(rangeString.indexOf("=") + 1, rangeString.indexOf("-")));
		//拖动进度条时的断点，其中10000是上面的视频文件大小，改成你的就好
		response.setHeader("Content-Range", String.valueOf(range + (file.length()-1)));
		response.setHeader("Accept-Ranges", "bytes");
		String suffix = filename.substring(filename.lastIndexOf(".")+1,filename.length());
		response.setHeader("Content-Disposition", "attachment;filename=" + System.currentTimeMillis() + suffix);
		writeFileToResponse(file,response);
	}

	@ApiOperation("视频播放接口")
	@GetMapping("play")
	public void play(@RequestParam(name="filename",required=true)String filename,HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.reset();
		filename = decryptFilePath+ File.separator + filename;
		File file = new File(filename);
		long fileLength = file.length();
		// 随机读文件
		RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");

		//获取从那个字节开始读取文件
		String rangeString = request.getHeader("Range");
		long range=0;

		range = Long.valueOf(rangeString.substring(rangeString.indexOf("=") + 1, rangeString.indexOf("-")));

		//获取响应的输出流
		OutputStream outputStream = response.getOutputStream();
		//设置内容类型
		response.setHeader("Content-Type", "video/mp4");
		//返回码需要为206，代表只处理了部分请求，响应了部分数据
		response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);

		// 移动访问指针到指定位置
		randomAccessFile.seek(range);
		// 每次请求只返回5MB的视频流
		byte[] bytes = new byte[1024 * 1024 * 5];
		int len = randomAccessFile.read(bytes);
		//设置此次相应返回的数据长度
		response.setContentLength(len);
		//设置此次相应返回的数据范围
		response.setHeader("Content-Range", "bytes "+range+"-"+(fileLength-1)+"/"+fileLength);
		// 将这1MB的视频流响应给客户端
		outputStream.write(bytes, 0, len);
		outputStream.close();
		randomAccessFile.close();

	}



	@RequestMapping(value = "download_img",method = RequestMethod.GET)
	@ApiOperation("图片下载接口")
	public void downloadImgFile(@RequestParam(name="filename",required=true)String filename,HttpServletRequest request, HttpServletResponse response){
		filename = uploadImgPath + filename;
		File file = new File(filename);
		//设置返回文件大小
		response.setContentLength(Integer.valueOf(file.length()+""));
		//设置返回类型
		try {
			response.setContentType(Files.probeContentType(Paths.get(filename)));
		} catch (Exception e) {
			e.printStackTrace();
		}
		String suffix = filename.substring(filename.lastIndexOf(".")+1,filename.length());
		response.setHeader("Content-Disposition", "attachment;filename=" + System.currentTimeMillis()+"."+suffix);
		writeFileToResponse(file,response);
	}
	
	/**
	 * 将文件流读出放入至指定的response
	 * @param file
	 * @param response
	 */
	private void writeFileToResponse(File file,HttpServletResponse response){
		byte[] buff = new byte[1024];
		FileInputStream fis = null;
		BufferedInputStream bis = null;
		try {
			fis = new FileInputStream(file);
			bis = new BufferedInputStream(fis);
			ServletOutputStream outputStream = response.getOutputStream();
			int i = bis.read(buff);
			while(i != -1){
				try {
					outputStream.write(buff, 0, i);
					i = bis.read(buff);
				} catch (Exception e) {
					// TODO: handle exception
				}				
			}
			bis.close();
			fis.close();
		} catch (Exception e) {

		}


	}


}
